# -*- coding: utf-8 -*-
#
# @Time    ： 2024/4/3  12:36
# @Auther  ： 徐良
# File     :  middleServicePanel.py

from typing import Any, Dict
import share.globalvar as gol
from PySide6.QtWidgets import QMainWindow, QApplication, QWidget, QVBoxLayout, QSizePolicy, QSpacerItem, \
    QTabBar
from ui.mideleServiceUI import Ui_MainWindow
from PySide6.QtGui import QGuiApplication, QIcon, QAction
from PySide6.QtCore import Qt
from mesParts.tabWidget.mainTab import TabWidget
from mesParts.button.buttons import PushButtonToolbox
from systemSet.aboutPanel import AboutPanel
from css.tabWidgetCss import tabBarStyle
from mesParts.toolBox.toolBoxs import AnimatedToolBox
import importlib
from dbService.db_service import get_model
from baseClass.tools.tableToList import TableToListForPC
from baseClass.tools.menu_action_item_tool import (get_menu_mode,
                                                   get_action_model,
                                                   get_browse_action_model,
                                                   get_edit_action_model,
                                                   get_navigation_config)

from baseClass.tools.dialogUtils import DialogUtils, StandardButton
import os
import ast

gol.init()
current_path = os.path.dirname(os.path.abspath(__file__))


class MiddleServicePanel(QMainWindow, Ui_MainWindow):
    """
    主面板
    """

    def __init__(self, parent=None, *args, **kwargs):
        """
        主界面
        :param parent:
        :param args:
        :param kwargs:
        """
        super().__init__(parent, *args, **kwargs)
        self.about = None
        self.setupUi(self)
        self.splitter.setSizes([30, 100])

        self.pageStyle = '单页面界面'
        self.toolFlag = 'browse'  # 工具栏默认为界面为浏览界面（针对多页面面板而言）

        self.toolBar.actionTriggered[QAction].connect(self.process_trigger)

        self.center()  # 将界面放置屏幕中央
        self.set_tool_boxs()  # 设置工具箱（分系统,page)
        self.set_menu('00.01')
        self.set_toolbar_action('00.01')

        self.tabWidget.setTabsClosable(False)   # 主看台面板不允许关闭
        self.tabWidget.tabCloseRequested.connect(self.close_tab)

        # gol.setValue('baseDbType', self.baseDbType)
        # gol.setValue('ToolBar', self.toolBar)
        # gol.setValue('MenuBar', self.menuBar())
        # gol.setValue('actionTriggered', self.process)

        self.tabWidget.currentChanged.connect(self.tabChanged)


    # region 设置界面居中，创建左侧导航
    def center(self):
        # 获取屏幕坐标
        screen = QGuiApplication.primaryScreen().geometry()  # 获取屏幕类并调用geometry()方法获取屏幕大小
        width = screen.width()  # 获取屏幕的宽
        height = screen.height()  # 获取屏幕的高
        size = self.geometry()
        newLeft = int((width - size.width()) / 2)
        newTop = int((height - size.height()) / 2)
        self.move(newLeft, newTop)
        self.statusbar.showMessage('就绪', 5000)

    def set_tool_boxs(self) -> None:
        """
        定义左边导航tab,工具箱部件,模块
        :return:
        """
        def createButtons(page, idx, item_all_list):
            if len(item_all_list) <= 0:         # 全部page的item列表
                return

            item_list = item_all_list[idx]       # 指定page的item列表
            count = len(item_list)
            if count <= 0:
                return

            layout = QVBoxLayout(page)
            for i in range(0, count):
                btn = PushButtonToolbox(self)
                btn.setObjectName('module_' + item_list[i]['fnumber'])
                btn.setText(' ' + item_list[i]['fname'])
                # btn.setIcon(QIcon(ll[i]['ficon']))
                # btn.setToolTip(ll[i]['ftooltip'])
                btn.clicked.connect(self.on_button_clicked)

                layout.addWidget(btn)

            verticalSpacer = QSpacerItem(20, 40, QSizePolicy.Minimum, QSizePolicy.Expanding)
            layout.addItem(verticalSpacer)

        sql = "select FBook,FBookName from t_navigation group by FBook order by FBook"
        page_mode = get_model(sql)      #   获取系统的分页
        rows = page_mode.rowCount()

        nav_tab = TabWidget()                   # 导航tabWidget
        nav_tab.setStyleSheet(tabBarStyle)
        self.verticalLayout.addWidget(nav_tab)

        for row in range(0, rows):
            book_num = page_mode.record(row).value('FBook')
            book_name = page_mode.record(row).value('FBookName')
            # 创建工具箱
            toolBox = AnimatedToolBox(self)
            tab_num = nav_tab.addTab(toolBox, book_name)   # 返回Tab的索引


        #     # 左边TAB图标
        #     icon = QIcon.fromTheme(iconList[row])
        #     myMainTab.setTabIcon(tab_index, icon)

        #     # 对每个Tab增加该toolbox
            sql = f"select * from t_navigation where FBook={book_num} and FLevel>=2 order by FBook,FItemXh,FNumber"
            table_dict = TableToListForPC(sql)  # 获取父记录和子记录的列表
            p_dict = table_dict.get_list_dict()
            p_parent_list = p_dict['list']  # 父list
            child_list = p_dict['childList']  # 子list
            p_row = len(p_parent_list)
            for index in range(0, p_row):
                tool_page = QWidget(self)        # 工具箱的页
                tool_page_name = p_parent_list[index]['fname']
                tool_page.setObjectName(tool_page_name)
                toolBox.addItem(tool_page, tool_page_name)
        #         toolBox.setItemIcon(index, QIcon(plist[index]['ficon']))
        #         toolBox.setItemToolTip(index, plist[index]['ftooltip'])


                createButtons(tool_page, index, child_list)
    # endregion


    # region 创建菜单、工具栏action
    def set_menu(self, number:str, tool_flag: str=None) -> None:
        """设置菜单"""
        self.menuBar().clear()
        menu_model = get_menu_mode(number)
        self.create_menu(menu_model)

    def create_menu(self, model):

        def set_child_menu(child_model, pid, cm):
            j = child_model.rowCount()
            for j in range(0, j):
                if pid == child_model.record(j).value('fparentid'):
                    if child_model.record(j).value('fdetail') == 0:
                        fa = cm.addMenu(child_model.record(j).value('fname'))
                        set_child_menu(child_model, child_model.record(j).value('fid'), fa)
                    else:
                        fx = QAction(child_model.record(j).value('fname'), self)
                        cm.addAction(fx)
                        fx.triggered.connect(self.process)

        rows = model.rowCount()
        for i in range(0, rows):
            if model.record(i).value('fdetail') == 0 and model.record(i).value('flevel') >= 3:
                cmenu = self.menuBar().addMenu(model.record(i).value('fname'))
                set_child_menu(model, model.record(i).value('fid'), cmenu)

    def create_toolbar_action(self, model) -> None:
        """创建工具栏命令"""
        self.toolBar.clear()
        count = model.rowCount()
        actionList = []
        for row in range(0, count):
            rec = model.record(row)
            if rec.value('fvisible') == 1:
                if rec.value('fname') != 'addSeparator':
                    newAction = QAction(QIcon(rec.value('ficon')),
                                        rec.value('fname'), self)
                    newAction.setObjectName(rec.value('fobjectname'))
                    newAction.setToolTip(rec.value('ftooltip'))

                    if rec.value('fenable'):
                        newAction.setEnabled(True)
                    else:
                        newAction.setEnabled(False)

                    self.toolBar.addAction(newAction)
                    actionList.append(newAction)
                else:
                    self.toolBar.addSeparator()
        gol.set_value('actionList', actionList)  # 用于工具栏命令设置“禁用/有效“

    def set_toolbar_action(self, number: str, tool_flag: str=None) -> None:
        """设置工具栏"""

        if self.pageStyle == '单页面界面':
            action_model = get_action_model(number)
        else:
            if tool_flag is None or tool_flag == 'browse':
               action_model = get_browse_action_model(number)
            elif tool_flag == 'edit':
                action_model = get_edit_action_model(number)
            else:
                action_model = get_browse_action_model(number)

        self.create_toolbar_action(action_model)

    # endregion


    # region 界面命令动作
    def process_trigger(self, q):
        # 直接指定执行当前tab下的actionDo
        if self.tabWidget.currentIndex() > 0:
            currentTab = self.tabWidget.currentWidget()
            currentTab.action_do(self, q)
        else:
            self.action_do(q)

    def process(self) -> None:
        """
        接受来自菜单的命令
        :return:
        """
        obj = QAction()
        q = self.sender().text()
        obj.setText(q)

        if self.tabWidget.currentIndex() > 0:
            currentTab = self.tabWidget.currentWidget()
            currentTab.action_do(self, obj)
        else:
            self.action_do(obj)

    def action_do(self, q) -> None:

        if q.text() == '退出':
            app = QApplication.instance()
            # userDict = gol.getValue('userDict')
            # currentPath = gol.getValue('currentPath')
            #
            # mesini = RwIni(currentPath)
            # mesini.writeUserInfo(userDict)
            app.quit()

        elif q.text() == '更换操作员':
            pass
            # self.menu_relogin()

        elif q.text() == '更改密码':
            self.changePassword()

        elif q.text() == '关于':
            self.about_panel()

        elif q.text() == "帮助":
            DialogUtils.info(text='正在开发')

    def about_panel(self) -> None:
        self.about = AboutPanel()
        self.about.show()

    def on_button_clicked(self) -> None:

        btn = self.sender()
        blist = btn.objectName().split('_')
        num = blist[1]
        item_dict = get_navigation_config(num)

        if not item_dict or item_dict['fclass'] == '':
            DialogUtils.info(text='正在开发')
            return


        package = item_dict['fpackage']
        lib = importlib.import_module(package)
        f_class = item_dict['fclass']
        f_para = item_dict['fpara'].strip()
        tab = None
        try:
            # 用 getattr 反射获取类
            # 相当于执行 lib.FNumberImport（假设 f_class 是 FNumberImport）
            cls = getattr(lib, f_class)
            # 直接传递解析后的字典
            if f_para:
                # 解析参数字符串为字典（保留你原本的逻辑，正确且安全）
                para_dict: Dict[str, Any] = ast.literal_eval(f_para)
                # 实例化类（直接传字典参数，符合 Python 规范）
                tab = cls(para_dict)
            else:
                # 无参数时直接实例化
                tab = cls()

        except AttributeError:
            DialogUtils.error(text=f"模块 {package} 中未找到类 {f_class}")
            return
        except (SyntaxError, ValueError) as e:
            DialogUtils.error(text=f"参数格式错误：{f_para}\n错误详情：{str(e)}")
            return
        except Exception as e:
            DialogUtils.error(text=f"实例化类失败\n错误详情：{str(e)}", detailed_text=str(e))
            return

        if tab is not None:
            tab.setObjectName("Form_" + num)
            self.add_this_tab_widget(tab, item_dict['fname'])


    # endregion


    # region 面板切换, 面板增加， 面板删除
    def tabChangeBefore(self):
        return True

    def tabChanged(self, index):
        tab = self.tabWidget.currentWidget()  # 判别是否为QStackedWidget面板,存在交替

        if hasattr(tab, 'stackedW'):
            self.tf = tab.stackedW
            self.toolFlag = tab.toolbarFlag  # 多页面， browse, edit
            if self.tf == "Yes":
                self.pageStyle = '多页面界面'
            else:
                self.pageStyle = '单页面界面'
        else:
            self.pageStyle = '单页面界面'

        # 获取当前tab的名称
        tab_name = self.tabWidget.currentWidget().objectName()
        if tab_name == 'main_0001':
            action_num = '00.01'
        else:
            action_num = tab_name[5: 13]

        self.set_menu(action_num)
        self.set_toolbar_action(action_num)

        # tab界面完成工具栏设置
        tab.toolbarFinish = 1


    # 新增并设置Tab

    def add_this_tab_widget(self, tab, name):
        self.tabWidget.setTabsClosable(True)
        nindex = self.tabWidget.count()
        self.tabWidget.addTab(tab, name)
        self.tabWidget.setCurrentIndex(nindex)
        self.tabWidget.tabBar().setTabButton(0, QTabBar.RightSide, None)

    def before_tab_close(self, obj):
        # 要执行tab中的某个函数
        if hasattr(obj, "closeOtherWin"):
            obj.closeOtherWin()

    def close_tab(self):

        self.tabWidget.setTabsClosable(False)
        self.tabWidget.setTabsClosable(True)
        index = self.tabWidget.currentIndex()

        self.before_tab_close(self.tabWidget.currentWidget())

        if index > 0:
            obj = self.tabWidget.currentWidget()
            if hasattr(obj, 'saveFlag'):  # 判断是否存在有数据要保存
                if obj.saveFlag:
                    obj.close()
            self.tabWidget.removeTab(index)

        self.tabWidget.tabBar().setTabButton(0, QTabBar.RightSide, None)
    # endregion


    # 菜单上的更改密码
    def changePassword(self):
        # self.changePW = ChangePasswordPanel()
        # self.changePW.show()
        pass

    # endregion



if __name__ == '__main__':
    import sys

    app = QApplication(sys.argv)
    window = MiddleServicePanel()
    window.show()
    sys.exit(app.exec())
